Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | /** * API route for worksheet review progress * * GET /api/curriculum/[playerId]/attachments/[attachmentId]/review-progress * - Get current review progress for resumable reviews * * PATCH /api/curriculum/[playerId]/attachments/[attachmentId]/review-progress * - Update review progress (save position, mark problems reviewed) * * POST /api/curriculum/[playerId]/attachments/[attachmentId]/review-progress * - Initialize review progress when starting a new review */ import { NextResponse } from 'next/server' import { eq } from 'drizzle-orm' import { z } from 'zod' import { db } from '@/db' import { practiceAttachments } from '@/db/schema/practice-attachments' import { withAuth } from '@/lib/auth/withAuth' import { canPerformAction } from '@/lib/classroom' import { getUserId } from '@/lib/viewer' import { type ReviewProgress, type WorksheetParsingResult, type ParsedProblem, createInitialReviewProgress, } from '@/lib/worksheet-parsing' // Confidence threshold for auto-approval const AUTO_APPROVE_THRESHOLD = 0.85 /** * Count problems that should be auto-approved based on confidence */ function countAutoApprovedProblems(problems: ParsedProblem[]): number { return problems.filter((p) => { const minConfidence = Math.min(p.termsConfidence, p.studentAnswerConfidence) return minConfidence >= AUTO_APPROVE_THRESHOLD && !p.excluded }).length } /** * Initialize review progress for a parsed worksheet */ function initializeReviewProgress(parsingResult: WorksheetParsingResult): { reviewProgress: ReviewProgress updatedProblems: ParsedProblem[] } { const problems = parsingResult.problems let autoApprovedCount = 0 // Mark high-confidence problems as auto-approved const updatedProblems = problems.map((problem) => { const minConfidence = Math.min(problem.termsConfidence, problem.studentAnswerConfidence) if (minConfidence >= AUTO_APPROVE_THRESHOLD && !problem.excluded) { autoApprovedCount++ return { ...problem, reviewStatus: 'approved' as const, reviewedAt: new Date().toISOString(), } } return { ...problem, reviewStatus: 'pending' as const, reviewedAt: null, } }) const reviewProgress = createInitialReviewProgress(problems.length, autoApprovedCount) return { reviewProgress, updatedProblems } } /** * GET - Get current review progress */ export const GET = withAuth(async (_request, { params }) => { try { const { playerId, attachmentId } = (await params) as { playerId: string; attachmentId: string } if (!playerId || !attachmentId) { return NextResponse.json({ error: 'Player ID and Attachment ID required' }, { status: 400 }) } // Authorization check const userId = await getUserId() const canView = await canPerformAction(userId, playerId, 'view') if (!canView) { return NextResponse.json({ error: 'Not authorized' }, { status: 403 }) } // Get attachment record const attachment = await db .select() .from(practiceAttachments) .where(eq(practiceAttachments.id, attachmentId)) .get() if (!attachment || attachment.playerId !== playerId) { return NextResponse.json({ error: 'Attachment not found' }, { status: 404 }) } // If no parsing result, can't have review progress if (!attachment.rawParsingResult) { return NextResponse.json({ error: 'Attachment has not been parsed' }, { status: 400 }) } // Return existing review progress or create default const reviewProgress = attachment.reviewProgress ?? createInitialReviewProgress( attachment.rawParsingResult.problems.length, countAutoApprovedProblems(attachment.rawParsingResult.problems) ) return NextResponse.json({ reviewProgress, problems: attachment.rawParsingResult.problems, totalProblems: attachment.rawParsingResult.problems.length, }) } catch (error) { console.error('Error getting review progress:', error) return NextResponse.json({ error: 'Failed to get review progress' }, { status: 500 }) } }) /** * POST - Initialize review progress (start a new review) */ export const POST = withAuth(async (_request, { params }) => { try { const { playerId, attachmentId } = (await params) as { playerId: string; attachmentId: string } if (!playerId || !attachmentId) { return NextResponse.json({ error: 'Player ID and Attachment ID required' }, { status: 400 }) } // Authorization check const userId = await getUserId() const canModify = await canPerformAction(userId, playerId, 'start-session') if (!canModify) { return NextResponse.json({ error: 'Not authorized' }, { status: 403 }) } // Get attachment record const attachment = await db .select() .from(practiceAttachments) .where(eq(practiceAttachments.id, attachmentId)) .get() if (!attachment || attachment.playerId !== playerId) { return NextResponse.json({ error: 'Attachment not found' }, { status: 404 }) } if (!attachment.rawParsingResult) { return NextResponse.json({ error: 'Attachment has not been parsed' }, { status: 400 }) } // Initialize review progress const { reviewProgress, updatedProblems } = initializeReviewProgress( attachment.rawParsingResult ) // Update the parsing result with review status on each problem const updatedParsingResult: WorksheetParsingResult = { ...attachment.rawParsingResult, problems: updatedProblems, } // Save to database await db .update(practiceAttachments) .set({ reviewProgress, rawParsingResult: updatedParsingResult, }) .where(eq(practiceAttachments.id, attachmentId)) return NextResponse.json({ success: true, reviewProgress, problems: updatedProblems, message: reviewProgress.autoApprovedCount > 0 ? `${reviewProgress.autoApprovedCount} problems auto-approved, ${reviewProgress.flaggedCount} need review` : `${updatedProblems.length} problems ready for review`, }) } catch (error) { console.error('Error initializing review progress:', error) return NextResponse.json({ error: 'Failed to initialize review progress' }, { status: 500 }) } }) // Schema for PATCH request const UpdateReviewProgressSchema = z.object({ // Update overall progress currentIndex: z.number().int().min(0).optional(), status: z.enum(['not_started', 'in_progress', 'completed']).optional(), // Update a specific problem's review status problemUpdate: z .object({ index: z.number().int().min(0), reviewStatus: z.enum(['pending', 'approved', 'corrected', 'flagged']), }) .optional(), }) /** * PATCH - Update review progress */ export const PATCH = withAuth(async (request, { params }) => { try { const { playerId, attachmentId } = (await params) as { playerId: string; attachmentId: string } if (!playerId || !attachmentId) { return NextResponse.json({ error: 'Player ID and Attachment ID required' }, { status: 400 }) } // Parse request body let body: z.infer<typeof UpdateReviewProgressSchema> try { const rawBody = await request.json() body = UpdateReviewProgressSchema.parse(rawBody) } catch (err) { return NextResponse.json( { error: 'Invalid request body', details: err instanceof Error ? err.message : 'Unknown', }, { status: 400 } ) } // Authorization check const userId = await getUserId() const canModify = await canPerformAction(userId, playerId, 'start-session') if (!canModify) { return NextResponse.json({ error: 'Not authorized' }, { status: 403 }) } // Get attachment record const attachment = await db .select() .from(practiceAttachments) .where(eq(practiceAttachments.id, attachmentId)) .get() if (!attachment || attachment.playerId !== playerId) { return NextResponse.json({ error: 'Attachment not found' }, { status: 404 }) } if (!attachment.rawParsingResult) { return NextResponse.json({ error: 'Attachment has not been parsed' }, { status: 400 }) } // Get current review progress or initialize let reviewProgress: ReviewProgress = attachment.reviewProgress ?? createInitialReviewProgress( attachment.rawParsingResult.problems.length, countAutoApprovedProblems(attachment.rawParsingResult.problems) ) let parsingResult = attachment.rawParsingResult // Apply updates const now = new Date().toISOString() // Update current index if provided if (body.currentIndex !== undefined) { reviewProgress = { ...reviewProgress, currentIndex: body.currentIndex, lastReviewedAt: now, } } // Update status if provided if (body.status !== undefined) { reviewProgress = { ...reviewProgress, status: body.status, lastReviewedAt: now, } } // Update a specific problem's review status if (body.problemUpdate) { const { index, reviewStatus } = body.problemUpdate if (index < 0 || index >= parsingResult.problems.length) { return NextResponse.json({ error: 'Invalid problem index' }, { status: 400 }) } const oldStatus = parsingResult.problems[index].reviewStatus ?? 'pending' // Update the problem parsingResult = { ...parsingResult, problems: parsingResult.problems.map((p, i) => i === index ? { ...p, reviewStatus, reviewedAt: now } : p ), } // Update counts based on status change if (oldStatus !== reviewStatus) { // Decrement old count if (oldStatus === 'pending' || oldStatus === 'flagged') { reviewProgress = { ...reviewProgress, flaggedCount: Math.max(0, reviewProgress.flaggedCount - 1), } } else if (oldStatus === 'approved') { reviewProgress = { ...reviewProgress, manuallyReviewedCount: Math.max(0, reviewProgress.manuallyReviewedCount - 1), } } else if (oldStatus === 'corrected') { reviewProgress = { ...reviewProgress, correctedCount: Math.max(0, reviewProgress.correctedCount - 1), } } // Increment new count if (reviewStatus === 'pending' || reviewStatus === 'flagged') { reviewProgress = { ...reviewProgress, flaggedCount: reviewProgress.flaggedCount + 1, } } else if (reviewStatus === 'approved') { reviewProgress = { ...reviewProgress, manuallyReviewedCount: reviewProgress.manuallyReviewedCount + 1, } } else if (reviewStatus === 'corrected') { reviewProgress = { ...reviewProgress, correctedCount: reviewProgress.correctedCount + 1, } } } reviewProgress = { ...reviewProgress, lastReviewedAt: now, status: 'in_progress', } // Check if all problems are reviewed const allReviewed = parsingResult.problems.every( (p) => p.reviewStatus === 'approved' || p.reviewStatus === 'corrected' || p.excluded ) if (allReviewed) { reviewProgress = { ...reviewProgress, status: 'completed' } } } // Save to database await db .update(practiceAttachments) .set({ reviewProgress, rawParsingResult: parsingResult, }) .where(eq(practiceAttachments.id, attachmentId)) return NextResponse.json({ success: true, reviewProgress, problems: parsingResult.problems, }) } catch (error) { console.error('Error updating review progress:', error) return NextResponse.json({ error: 'Failed to update review progress' }, { status: 500 }) } }) |